package cn.jetpiece.cloud.modular.doc;

import cn.jetpiece.cloud.resource.annotation.keys.ResourceKey;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.config.GatewayProperties;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.support.NameUtils;
import org.springframework.data.redis.core.RedisTemplate;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 聚合各个服务的swagger接口
 */
@Slf4j
@AllArgsConstructor
public class JetpieceSwaggerResourceProvider implements SwaggerResourcesProvider {
    private final RouteLocator routeLocator;
    private final GatewayProperties gatewayProperties;
    private final RedisTemplate<String, Object> redisTemplate;

    @Override
    public List<SwaggerResource> get() {
        List<SwaggerResource> resources = new ArrayList<>();
        List<String> routes = new ArrayList<>();
        // 只抽取后缀为Swagger的路由信息
        routeLocator.getRoutes().subscribe(route -> routes.add(route.getId()));

        gatewayProperties.getRoutes().stream().filter(routeDefinition -> routes.contains(routeDefinition.getId())).forEach(route -> route.getPredicates().stream()
                .filter(predicateDefinition -> ("Path").equalsIgnoreCase(predicateDefinition.getName()))
                .forEach(predicateDefinition -> resources.addAll(swaggerResource(route.getId(),
                        predicateDefinition.getArgs().get(NameUtils.GENERATED_NAME_PREFIX + "0")
                                .replace("/**", "")))));

        return resources;
    }

    @SuppressWarnings("all")
    private List<SwaggerResource> swaggerResource(String serviceId, String location) {
        log.info("serviceId:{},location:{}", serviceId, location);
        String name = serviceId;
        Set<Object> keySet = redisTemplate.boundHashOps(ResourceKey.API_DOC).keys();
        if (keySet == null) {
            return new ArrayList<>();
        }
        String key = serviceId;
        for (Object obj : keySet) {
            if (obj instanceof String && ((String) obj).contains(location.substring(1, location.length()))) {
                key = (String) obj;
                String[] str = key.split(ResourceKey.RES_METHOD_URL_SEPARATOR);
                name = str[1];
            }
        }
        final String finalName = name;
        List<SwaggerResource> serviceResource = (List<SwaggerResource>) redisTemplate.boundHashOps(ResourceKey.API_DOC).get(key);
        if (serviceResource == null) {
            return new ArrayList<>();
        }
        List<SwaggerResource> newList = new ArrayList<>();
        assert serviceResource != null;
        serviceResource.forEach(swaggerResource -> {
            SwaggerResource newSwaggerResource = new SwaggerResource();
            newSwaggerResource.setName(finalName + ResourceKey.RES_METHOD_URL_SEPARATOR + swaggerResource.getName());
            newSwaggerResource.setLocation(location + swaggerResource.getUrl());
            newSwaggerResource.setUrl(location + swaggerResource.getUrl());
            newSwaggerResource.setSwaggerVersion("2.0");
            newList.add(newSwaggerResource);

        });
        return newList;
    }

}
